package com.jdk.learn.juc2.thread.excrise;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 类功能描述:
 * 等待线程A和B处理完业务
 * 有问题 会死锁
 *
 * @author bgt
 * @version V1.0
 * @since 2019-02-21 13:39
 */
public class PrintABByCondition {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        Thread printA = new Thread(()->{
                try {
                    lock.lock();
                    while (count.get() < 20) {
                        System.out.print("A");
                        count.incrementAndGet();
                        conditionB.signal();
                        if (count.get() < 20){
                            conditionA.await();
                        }
                    }
                    conditionA.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

        },"printA");
        Thread printB = new Thread(()-> {
                try {
                    lock.lock();
                    while (count.get() < 20) {
                        System.out.print("B  ");
                        count.incrementAndGet();
                        conditionA.signal();
                        if (count.get() <20){
                            conditionB.await();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
        },"printB");
        printA.start();
        Thread.sleep(1);
        printB.start();
    }

}
